from plyny.presentation.table import Table


import string

class TextTable(Table):
    def render(self):
        return make_simple_table(self._format(), False, self.justifications, None)


def make_simple_table(rows, distinct_final_row=False, justifications=None, cols=None):
    # assume that all rows have same number of columns
    if not cols:
        cols = len(rows[0])

    if justifications is None:
        justifications = [2] * cols
    else:
        justifications = justifications[:]

    for i, justification in enumerate(justifications):
        if justification == 0:
            j = string.ljust
        elif justification == 1:
            j = string.center
        else:
            j = string.rjust

        justifications[i] = j


    sizes = [-1] * cols

    for row in rows:
        if not row:
            continue
        for i in xrange(cols):
            sizes[i] = max(sizes[i], len(row[i]))

    l = sum((size + 3) for size in sizes) - 1

    lines = []

    horiz_line = '+' + '-' * l + '+'

    lines.append(horiz_line)

    for i, row in enumerate(rows):
        if not row:
            lines.append(horiz_line)
        else:
            line = ''
            for j, item in enumerate(row):
                if i == 0:
                    just = string.center
                else:
                    just = justifications[j]
                if not isinstance(item, unicode):
                    item = unicode(item, 'utf-8')
                line += '| ' + just(item, sizes[j]) + ' '
            line += '|'
            lines.append(line)
        if i == 0:
            lines.append(horiz_line)

    lines.append(horiz_line)

    return u'\n'.join(lines)

if __name__ == '__main__':
    t = TextTable('a', 'b', 'c', 'ed')
    t.add(1, 2, 3, 4)
    t.add(5, 6, 7, 8)
    print t.render()
